<?php
class Cli_Notify extends CLI
{
	public function main()
	{
        $notify_id_array = DB::select( 'notify_id' )
			->from( 'notify' )
            ->fetch_all();
        $count = count($notify_id_array);
        cli::output("\n总共{$count}条记录");
        $i = 0;
        foreach ( $notify_id_array as $notify_id )
        {
            $content = $this->body( $notify_id['notify_id'] );
            DB::update( 'notify' )->set( array( 'content' => $content ) )->where( 'notify_id', '=', $notify_id['notify_id'] )->execute();
            echo '>';
            $i++;
        }
        cli::output("\n成功转换{$i}条记录");
    }
    
    /**
     * 系统通知信息封装
     *
     * @param  mixed   $member_id
     * @param  string  $content
     */
	public function body( $notify_id )
	{
		//$config = Cache::instance()->get('site_config');
		$data_template = array(
			'nickname' => '{nickname}',
			'shop_url' => 'http://shop.360hqb.com/{shop_id}/index.html',
			'shop_name' => '<a href="http://shop.360hqb.com/{shop_id}/index.html" target="_blank">{shop_name}</a>',
			'发货' => '<a href="http://my.360hqb.com/seller/order/view/{order_sn}" target="_blank">发货</a>',
		);
		$result = DB::select('content','shop_id','member_id','template_body','template_data')
			->from( 'notify' )
			->where( 'notify_id', '=', $notify_id )
			->fetch_row();
		$data_template['收货'] = '<a href="http://my.360hqb.com/'.(empty($result['member_id'])?'seller':'personal').'/order/view/{order_sn}" target="_blank">收货</a>';
		$data_template['订单'] = '<a href="http://my.360hqb.com/'.(empty($result['member_id'])?'seller':'personal').'/order/view/{order_sn}" target="_blank">订单</a>';
		extract($result);
		if($template_body!='')
		{
			$content = $template_body;
			//去除发货、收货、订单链接
			if(preg_match('/[发货|收货]/u', $content))
			{
				unset($data_template['订单']);
			}
			$template_data = json_decode($template_data);
			$template_data = is_object($template_data) ? $template_data : array();
			foreach($template_data as $k=>$v)
			{
				if(($k=='shop_id') && (($v==1) || ($v==2)))
				{
					continue;
				}

				foreach($data_template as $kk=>$vv)
				{
					$data_template[$kk] = str_replace("{{$k}}", $v, $vv);
				}
			}
			foreach($template_data as $k=>$v)
			{
				$content = str_replace("{{$k}}", isset($data_template[$k]) ? $data_template[$k] : $v, $content);
			}
			foreach($data_template as $k=>$v)
			{
				$content = str_replace("{$k}", $v, $content);
			}
		}
		return $content;
	}
}